from ftplib import FTP
import os


class RFtp:

    ftp = FTP()

    def __init__(self,host,port=21):
        self.ftp.connect(host,port)
        self.ftp.set_debuglevel(2)

    def login(self,username,pwd):
        self.ftp.set_debuglevel(0)
        self.ftp.login(username,pwd)
        print(self.ftp.welcome)

    def upload_file(self, localpath, remotepath, filename):
        os.chdir(localpath)   # change work dir
        self.ftp.cwd(remotepath)   # remote ftp dir
        file_handle = open(filename,"rb")   # open in write mode
        self.ftp.storbinary('STOR %s' % os.path.basename(filename),file_handle,blocksize=1024)  # download file

    def download_file(self,localpath,remotepath,filename):
        os.chdir(localpath)   # change work dir
        self.ftp.cwd( remotepath)   # remote ftp dir
        self.ftp.nlst()  # get files in remote dir
        file_handle = open(filename,"wb").write   # open in write mode
        self.ftp.retrbinary('RETR %s' % os.path.basename(filename),file_handle,blocksize=1024)  # download file

    def is_dir(self, name):
        try:
            self.ftp.cwd(name)
        except:
            return False
        else:
            self.ftp.cwd('..')
            return True

    def is_file(self, name):
        return not self.is_dir(name)

    def search_and_get_file_path(self, start_path:str, file_name: str):
        print('search dir: ' + start_path)
        self.ftp.cwd(start_path)
        lines = []
        self.ftp.retrlines('LIST', lines.append)
        entries = []
        for li in lines:
            entries.append(li.split()[-1])
        for ent in entries:
            print(ent)
            if ent == file_name and self.is_file(ent):
                return '/'.join([start_path, ent])
        # recurse to find the file
        for ent in entries:
            if ent != '.' and ent != '..' and self.is_dir(ent):
                res = self.search_and_get_file_path(('/'.join([start_path, ent])), file_name)
                if res is not None:
                    return res
                else:
                    self.ftp.cwd('..')

        return None

    def close(self):
        self.ftp.set_debuglevel(0)
        self.ftp.quit()


if __name__ == "__main__":
    ftp = RFtp('172.22.102.202')
    ftp.login('wangqiang', 'wangqiang')
    ftp.upload_file('/tmp/', '/Project/Switch/DLINK-ME/Firmware/B024/DGS-1210_ME_v7.03.Bxxx/DGS-1210-28-ME-B1/', 'test.txt')